package br.com.diego.system.manager.permissao.impl;

import br.com.diego.system.controller.consultapermissao.ConsultaPermissaoVo;
import br.com.diego.system.controller.consultapermissao.TipoVo;
import br.com.diego.system.entity.permissao.Permissao;
import br.com.diego.system.manager.AbstractDiegoManager;
import br.com.diego.system.manager.permissao.PermissaoManager;
import java.util.List;
import javax.persistence.OptimisticLockException;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

public class JpaPermissaoManagerImpl extends AbstractDiegoManager implements PermissaoManager {

    @Override
    @Transactional(readOnly = false)
    public void salvar(Permissao permissao) {
        if (permissao.getId() == null) {
            entityManager.persist(permissao);
        }else{
            try {     
                entityManager.merge(permissao);
            }catch(OptimisticLockException e){
                throw new IllegalArgumentException(
                        "Estes dados foram alterados por outro usuario.");
            }    
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void deletar(Permissao permissao) {
        permissao =  buscarPeloId(permissao.getId());
        entityManager.remove(permissao);
    }

    @Override
    @Transactional(readOnly = true)
    public Permissao buscarPeloId(Long id) {
        return entityManager.find(Permissao.class, id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Permissao> consultar(ConsultaPermissaoVo consultaPermissaoVo) {
        Session session = (Session) entityManager.getDelegate();
        Criteria criteria =  session.createCriteria(Permissao.class);
        if (consultaPermissaoVo.getUsuarioVo().getId() != null) {
            criteria.add(Restrictions.eq("usuario_id", consultaPermissaoVo.getUsuarioVo().getId()));
        }
        if (consultaPermissaoVo.getComponenteVo().getId() != null) {
            criteria.add(Restrictions.eq("componente_id", consultaPermissaoVo.getComponenteVo().getId()));
        }
        if (consultaPermissaoVo.getTipoVo() != TipoVo.TODOS) {
            criteria.add(Restrictions.eq("tipo", consultaPermissaoVo.getTipoVo()));
        }
        return criteria.list();
    }

    
}
